/**
 *@author Ivam Henrique Marques dos Santos
 *        email: ivam.santos@skytef.com.br
 *        skype: ivam.santos.skytef
 *        telefone: +55 11 96214-7543
 * */

package br.skytef.stmanager.beans;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import br.skytef.stmanager.daos.UsuarioDao;
import br.skytef.stmanager.entities.UsuarioEntity;

/**
 * Class Controller LoginBean
 * */

@ManagedBean(name="LoginBean")
@SessionScoped
public class LoginBean {  
	
	/**
	 * Campos com seus respectivos Getters e Setters.	  
	 */
	
	private static UsuarioEntity usuarioBD;	
	public static UsuarioEntity getUsuarioBD() {return usuarioBD;}
	public static void setUsuarioBD(UsuarioEntity usuarioBD) {LoginBean.usuarioBD = usuarioBD;}
	
	public String getUsername() {return username;}          
	public void setUsername(String username) {this.username = username;} 
	public String username;  
	
	public String getPassword() {return password;}  
	public void setPassword(String password) {this.password = password;}  
	private String password;  
	
	
	/**
	 * Métodos de controle.
	 */
	
	
	public LoginBean() {
		super();
		usuarioBD = new UsuarioEntity();
	}
	/**
	 * @param ActionEvent
	 * */
	public void login(ActionEvent actionEvent) throws IOException {  
		@SuppressWarnings("unused")
		boolean loggedIn = false;    

		if(username != null && password != null) {  
			usuarioBD = new UsuarioDao().buscar(username);

			if (usuarioBD != null ){

				if (usuarioBD.getLogin().equals(username)  && usuarioBD.getSenha().equals(password)){

					loggedIn = true;
										
					FacesContext facesContext = FacesContext.getCurrentInstance(); 
					facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Bem-vindo", username));
					FacesContext.getCurrentInstance().getExternalContext()  
					.redirect("dashboard.xhtml");
				}

				if (!(usuarioBD.getSenha().equals(password))){

					FacesContext facesContext = FacesContext.getCurrentInstance(); 
					facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"Erro ao acessar:", "Senha inválida"));
					FacesContext.getCurrentInstance().getExternalContext()  
					.redirect("../");
				}
			}
		} if (usuarioBD == null ){  
			loggedIn = false;
			FacesContext facesContext = FacesContext.getCurrentInstance(); 
			facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"Erro ao acessar:", "Usuário inválido"));
			FacesContext.getCurrentInstance().getExternalContext()  
			.redirect("../");
		}  

	}

}
